package com.gmrz.uaf.servlet.v1.servlet;

import com.gmrz.uaf.servlet.v1.handler.UAFRegRequestHandler;
import com.gmrz.util.Convert;
import com.gmrz.util.Strings;
import com.gmrz.webauthn.handler.WebRegRequestHandler;
import com.google.inject.Singleton;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;

/**
 * Created by gmrz-ops on 2017/7/12.
 */
@Singleton
public class UAFReqRequestServlet extends HttpServlet {
    private static final Logger LOG = LogManager.getLogger(UAFReqRequestServlet.class);

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // 先将请求转为字节输入流
        ServletInputStream inputStream = req.getInputStream();
        ByteArrayOutputStream content = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int lens = -1;
        while ((lens = inputStream.read(b)) > 0) {
            // 将字节输入流写入到字节数组输出流
            content.write(b, 0, lens);
        }
        // 将字节数组输出流进行utf-8编码转为字符串
        String request = content.toString("UTF-8");// 内容
        // 使用gson 获取请求json串中的信息放入到map集合中
        Map<String, Object> paramsMap = Convert.getInfoFromRequest(request);
        // 使用gson获取请求json串中的业务号信息；
        String transNo = Convert.getTransNoFromContext(request);
        // 将业务号数据放入到唯一标记threadcontext中
        ThreadContext.put("transNo", transNo);

        String response;
        // 判断请求是否为web浏览器发起的
        if ((paramsMap.get("protocol") != null) && (Strings.equals((String) paramsMap.get("protocol"), "web"))) {
            WebRegRequestHandler uafRegResponseHandler = new WebRegRequestHandler();
            response = uafRegResponseHandler.regInit(request);
        } else {
            UAFRegRequestHandler uafRegResponseHandler = new UAFRegRequestHandler();
            // handler中对请求进行业务处理并返回响应数据
            response = uafRegResponseHandler.regInit(request);
        }

        resp.getWriter().write(response);
    }
}
